package com.ruoyi.front;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.PhoneUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.code.kaptcha.Constants;
import com.ruoyi.common.config.ServerConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysMember;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.framework.shiro.nopassword.EasyUsernameToken;
import com.ruoyi.framework.shiro.service.SysPasswordService;
import com.ruoyi.front.service.WeChatService;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.mapper.SysMemberMapper;
import com.ruoyi.system.param.DataParam;
import com.ruoyi.system.param.PasswordParam;
import com.ruoyi.system.response.UserDoc;
import com.ruoyi.system.service.*;
import com.xkcoding.justauth.AuthRequestFactory;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.request.AuthAlipayRequest;
import me.zhyd.oauth.request.AuthRequest;
import me.zhyd.oauth.utils.AuthStateUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Controller
public class login extends footcontroller {
    @Value("${shiro.rememberMe.enabled: false}")
    private boolean rememberMe;
    @Autowired
    private ISysMemberService userService;
    @Autowired
    private SendSmsService sendSmsService;
    @Autowired
    private SysPasswordService passwordService;
    @Resource
    private RedisTemplate redisTemplate;
    //分类
    @Autowired
    private ISysTypeService iSysTypeService;
    //首页轮播图
    @Autowired
    private ISysBannerService iSysBannerService;
    //首页通告
    @Autowired
    private ISysNoticeService iSysNoticeService;
    //测试积分
    @Autowired
    private ISysPointpotService iSysPointpotService;
    //文档相关
    @Autowired
    private ISysDocService iSysDocService;
    @Autowired
    private ServerConfig serverConfig;
    @Autowired
    private ISysMemberService iSysMemberService;
    @Autowired
    private WeChatService weChatService;
    @Autowired
    private ISysLinksService iSysLinksService;
    @Autowired
    private ISysPartnerService iSysPartnerService;
    @Autowired
    ISysSiteService iSysSiteService;
    @Autowired
    ISysLoginsetService iSysLoginsetService;
    @Autowired
    ISysRegsetService iSysRegsetService;
    @Autowired
    private ISysSmtpService sysSmtpService;
    @Autowired
    private ISysSiteService sysSiteService;
    @Autowired
    private  ISysRegsetService sysRegsetService;
    @Autowired
    private ISysProtocolService sysProtocolService;
    @Autowired
    private ISysAdvService sysAdvService;
    @Autowired
    private ISysOsssetService sysOsssetService;
    @Autowired
    private  AuthRequestFactory factory;
    @GetMapping
    public List<String> list() {
        return factory.oauthList();
    }
    @GetMapping({"/","/index"})
    public String index(ModelMap modelMap){
        List<SysType> typeList = iSysTypeService.selectSysTypeList(new SysType());
        HashMap<Long, SysType> map=new HashMap<Long, SysType>();
        HashMap<Long, List<SysType>> hasharrlist = new HashMap<Long,List<SysType>>();
        List<SysType> tem = new ArrayList<SysType>();
        for (int i = 0; i < typeList.size(); i++) {
            map.put(typeList.get(i).getTypeid(),typeList.get(i));
        }
        for (Map.Entry<Long,SysType> entry : map.entrySet()) {

            if (hasharrlist.containsKey(entry.getValue().getPtypeid())) {
                hasharrlist.get(entry.getValue().getPtypeid()).add(entry.getValue());
            } else {
                tem.clear();
                tem.add(entry.getValue());
                List<SysType> list = new ArrayList<SysType>(tem);
                hasharrlist.put(entry.getValue().getPtypeid(), list);
            }
        }
        //轮播图
        List<SysBanner> sysBanners = iSysBannerService.selectSysBannerList(new SysBanner());
        //通告
        List<SysNotice> sysNotices = iSysNoticeService.selectNoticeList(new SysNotice());
        //积分循环
        List<SysPointpot> sysPointpots = iSysPointpotService.selectSysPointpotList1();
        //最新文档
         startPage();
         TableSupport.buildPageRequest().setPageSize(12); //设置页面大小
        SysDoc sysDoc = new SysDoc();
        sysDoc.setState(1);
        List<SysDoc> sysDocs = iSysDocService.selectSysDocList(sysDoc);
        SysOssset sysOssset;
        sysOssset = sysOsssetService.selectSysOsssetList(new SysOssset()).get(0);
        for (int i = 0;i<sysDocs.size();i++)
        {
            if(StringUtils.localFile(sysDocs.get(i).getPath())) {
                sysDocs.get(i).setPath(serverConfig.getUrl() + StringUtils.localpng(sysDocs.get(i).getPath()));
            }
            else if(sysOssset.getState()>0&&ossFileExist(StringUtils.osspng(sysDocs.get(i).getPath())))
            {
                sysDocs.get(i).setPath("https://"+sysOssset.getBucket()+"."+sysOssset.getEndpoint()+"/"+StringUtils.osspng(sysDocs.get(i).getPath()));
            }
            else
            {
                sysDocs.get(i).setPath("/img/doc.png");
            }
        }
        sysDoc = new SysDoc();
        sysDoc.setDownpay(BigDecimal.ZERO);
        startPage();
        List<SysDoc> sysDocList = iSysDocService.selectSysDocList(sysDoc);

        for (int i = 0;i<sysDocList.size();i++)
        {
            if(StringUtils.localFile(sysDocList.get(i).getPath())) {
                sysDocList.get(i).setPath(serverConfig.getUrl() + StringUtils.localpng(sysDocList.get(i).getPath()));
            }
            else if(sysOssset.getState()>0&&ossFileExist(StringUtils.osspng(sysDocList.get(i).getPath())))
            {
                sysDocList.get(i).setPath("https://"+sysOssset.getBucket()+"."+sysOssset.getEndpoint()+"/"+StringUtils.osspng(sysDocList.get(i).getPath()));
            }
            else
            {
                sysDocList.get(i).setPath("/img/doc.png");
            }
        }
        //VIP免费
        SysDoc sysDoc1 = new SysDoc();
        sysDoc1.setIsvip(1);
        startPage();
        List<SysDoc> sysDocList1 = iSysDocService.selectSysDocList(sysDoc1);

        for (int i = 0;i<sysDocList1.size();i++)
        {
            if(StringUtils.localFile(sysDocList1.get(i).getPath())) {
                sysDocList1.get(i).setPath(serverConfig.getUrl() + StringUtils.localpng(sysDocList1.get(i).getPath()));
            }
            else if(sysOssset.getState()>0&&ossFileExist(StringUtils.osspng(sysDocList1.get(i).getPath())))
            {
                sysDocList1.get(i).setPath("https://"+sysOssset.getBucket()+"."+sysOssset.getEndpoint()+"/"+StringUtils.osspng(sysDocList1.get(i).getPath()));
            }
            else
            {
                sysDocList1.get(i).setPath("/img/doc.png");
            }
        }
        //用户
        List<UserDoc> userDocList = iSysDocService.selectUserDocs();
        //关于我们 about.html
        getabout(modelMap);
        //友情链接和合作伙伴
        SysLinks sysLinks = new SysLinks();
        sysLinks.setState(1);
        List<SysLinks> sysLinksList = iSysLinksService.selectSysLinksList(sysLinks);
        SysPartner sysPartner = new SysPartner();
        sysPartner.setState(1);
        List<SysPartner> sysPartnerList = iSysPartnerService.selectSysPartnerList(sysPartner);
        modelMap.put("partner",sysPartnerList);
        modelMap.put("links",sysLinksList);
        modelMap.put("impuser",userDocList);
        modelMap.put("newdoc_vip",sysDocList1);
        modelMap.put("newdoc_free",sysDocList);
        modelMap.put("banner_array",sysBanners);
        modelMap.put("notice_array",sysNotices);
        modelMap.put("pointpot_array",sysPointpots);
        modelMap.put("type_array", hasharrlist);
        modelMap.put("newdoc_array",sysDocs);
        //导航
        modelMap.put("navurl",getRequest().getRequestURI());
        //广告管理
        SysAdv sysAdv = new SysAdv();
        sysAdv.setState(1);
        List<SysAdv> sysAdvList = sysAdvService.selectSysAdvList(sysAdv);
        modelMap.put("sysAdvList",sysAdvList);
        //****************/
        return "index";
    }
    @GetMapping({"/login"})
    public String login(ModelMap modelMap,HttpServletRequest request, @RequestParam(value = "redirectUrl", required = false) String redirectUrl){
        getabout(modelMap);
        List<SysLoginset> sysLoginsetList = iSysLoginsetService.selectSysLoginsetList(new SysLoginset());
        modelMap.put("loginsetlist",sysLoginsetList);
        //判断登录登录还是邮箱
        Boolean isphone = false;
        Boolean isemail = false;
        for (int i=0;i<sysLoginsetList.size();i++)
        {
            if (sysLoginsetList.get(i).getId()==3)
                isphone = sysLoginsetList.get(i).getState()>0?true:false;
            if (sysLoginsetList.get(i).getId()==4)
                isemail = sysLoginsetList.get(i).getState()>0?true:false;
        }
        modelMap.put("isphone",isphone);
        modelMap.put("isemail",isemail);
        //****************************/
        //************注册选项 *//
        SysRegset regset = iSysRegsetService.selectSysRegsetList(new SysRegset()).get(0);
        modelMap.put("regset",regset);
        SysProtocol protocol = sysProtocolService.selectSysProtocolList(new SysProtocol()).get(0);
        modelMap.put("protocol", protocol);
        //**********************/
        modelMap.put("isRemembered", rememberMe);
        return "login";
    }
    //login_f
    @GetMapping(value = {"/login_f.htm"})
    public String login_f(ModelMap modelMap) {
        List<SysLoginset> sysLoginsetList = iSysLoginsetService.selectSysLoginsetList(new SysLoginset());
        //判断登录登录还是邮箱
        Boolean isphone = false;
        Boolean isemail = false;
        for (int i=0;i<sysLoginsetList.size();i++)
        {
            if (sysLoginsetList.get(i).getId()==3)
                isphone = sysLoginsetList.get(i).getState()>0?true:false;
            if (sysLoginsetList.get(i).getId()==4)
                isemail = sysLoginsetList.get(i).getState()>0?true:false;
        }
        modelMap.put("isphone",isphone);
        modelMap.put("isemail",isemail);
        //****************************/
        //************注册选项 *//
        SysRegset regset = iSysRegsetService.selectSysRegsetList(new SysRegset()).get(0);
        modelMap.put("regset",regset);
        SysProtocol protocol = sysProtocolService.selectSysProtocolList(new SysProtocol()).get(0);
        modelMap.put("protocol", protocol);
        //**********************/
        modelMap.put("loginsetlist",sysLoginsetList);
        return "login_f";
    }
    @PostMapping("/login")
    @ResponseBody
    public AjaxResult ajaxLogin(String username, String password, Boolean rememberMe1)
    {


        //UsernamePasswordToken token = new UsernamePasswordToken(username, password, rememberMe1);
        EasyUsernameToken token = new EasyUsernameToken(username,password,rememberMe1);
        Subject subject = SecurityUtils.getSubject();
        try
        {
            subject.login(token);
            return success();
        }
        catch (AuthenticationException e)
        {
            String msg = "用户或密码错误";
            if (StringUtils.isNotEmpty(e.getMessage()))
            {
                msg = e.getMessage();
            }
            return error(msg);
        }
    }
    @PostMapping("/checkPhoneUnique")
    @ResponseBody
    public boolean checkPhoneUnique(String data)
    {
        return userService.checkPhoneUnique(data);
    }
    @PostMapping("/sendcode/phone")
    @ResponseBody
    public boolean sendMessage(String username)
    {

        //获取到操作String的对象
        ValueOperations<String,String> value = redisTemplate.opsForValue();

        //根据手机号查询
        String phone = value.get(username);
        //如果手机号在redis中不存在的话才进行验证码的发送
        if (StringUtils.isEmpty(phone)){
            //生成6位随机数
            String code = String.valueOf(Math.random()).substring(3, 9);
            //调用业务层
            boolean sendSmsFlag = sendSmsService.sendSms(username, code);
            if (sendSmsFlag){
                // 发送成功之后往redis中存入该手机号以及验证码 并设置超时时间 5 分钟
                redisTemplate.opsForValue().set(username,code, 5, TimeUnit.MINUTES);

            }
            System.out.println( "发送验证码到：" + username + "成功! " + "Message:" + sendSmsFlag);
        }else {
            //5分钟之类还是同一个验证码
            //根据key值查询
            String redisCode = value.get(username);
            boolean sendSmsFlag = sendSmsService.sendSms(username, redisCode);
            if (sendSmsFlag) {
                System.out.println("该手机号：" + username + " 剩余：" + redisTemplate.getExpire(username) + "秒后可再次进行发送！");
            }
        }
        return true;
    }
    @PostMapping("/sendcode/email")
    @ResponseBody
    public boolean sendMessageEmail(String username,HttpServletRequest request)
    {
        //生成6位随机数
        String code = String.valueOf(Math.random()).substring(3, 9);
        HttpSession session = request.getSession();
        session.setAttribute("emailcode", code);
        SysSmtp sysSmtp = sysSmtpService.selectSysSmtpList(new SysSmtp()).get(0);
        SysSite sysSite = sysSiteService.selectSysSiteList(new SysSite()).get(0);
        SysRegset sysRegset = sysRegsetService.selectSysRegsetList(new SysRegset()).get(0);
        JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
        // 设置主机地址（例如：smtp.gmail.com）
        mailSender.setHost(sysSmtp.getSmtp());
        // 设置端口（例如：587 或 465）
        mailSender.setPort(Integer.parseInt(sysSmtp.getPort()));
        // 设置需要认证
        mailSender.setUsername(sysSmtp.getEmail());
        mailSender.setPassword(sysSmtp.getPassword());
        // 设置属性
        Properties properties = new Properties();
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.starttls.enable", "true");
        mailSender.setJavaMailProperties(properties);

        String title = sysRegset.getInviteTitle();
        String body = sysRegset.getInviteBody();
        title = StringUtils.replace(title,"{code}",code);
        title = StringUtils.replace(title,"{sitename}",sysSite.getName());
        title = StringUtils.replace(title,"{adminemail}",sysSite.getEmail());
        body = StringUtils.replace(body,"{code}",code);
        body = StringUtils.replace(body,"{sitename}",sysSite.getName());
        body = StringUtils.replace(body,"{adminemail}",sysSite.getEmail());
        // 创建邮件内容
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        try {
            // 为邮件设置内容
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
            helper.setTo(username);
            helper.setFrom(sysSmtp.getEmail());
            helper.setSubject(title);
            helper.setText(body, true);
            // 发送邮件
            mailSender.send(mimeMessage);
            System.out.println("邮件发送成功");
        } catch (Exception e) {
            e.printStackTrace();
        }

      return  true;
    }
    @PostMapping (value = {"/c/yyzm"})
    @ResponseBody
    public Boolean checkemailcode(String data) {

        return  ShiroUtils.getSession().getAttribute("emailcode").equals(data);
    }
    @PostMapping("/sendcode/phone/f")
    @ResponseBody
    public boolean sendMessageForget(String username)
    {

        //获取到操作String的对象
        ValueOperations<String,String> value = redisTemplate.opsForValue();

        //根据手机号查询
        String phone = value.get(username);
        //如果手机号在redis中不存在的话才进行验证码的发送
        if (StringUtils.isEmpty(phone)){
            //生成6位随机数
            String code = String.valueOf(Math.random()).substring(3, 9);
            //调用业务层
            boolean sendSmsFlag = sendSmsService.sendSms_1(username, code);
            if (sendSmsFlag){
                // 发送成功之后往redis中存入该手机号以及验证码 并设置超时时间 5 分钟
                redisTemplate.opsForValue().set(username,code, 5, TimeUnit.MINUTES);

            }
            System.out.println( "发送验证码到：" + username + "成功! " + "Message:" + sendSmsFlag);
        }else {
            //5分钟之类还是同一个验证码
            //根据key值查询
            String redisCode = value.get(username);
            boolean sendSmsFlag = sendSmsService.sendSms_1(username, redisCode);
            if (sendSmsFlag) {
                System.out.println("该手机号：" + username + " 剩余：" + redisTemplate.getExpire(username) + "秒后可再次进行发送！");
            }
        }
        return true;
    }
    //验证手机验证码
    @GetMapping("/yyzm/{key}/{code}")
    @ResponseBody
    public boolean checkCode(@PathVariable("key") String number,
                            @PathVariable("code")String code){
        if(Validator.isEmail(number))
        {
            return  ShiroUtils.getSession().getAttribute("emailcode").equals(code);
        }
        //获取到操作String的对象
        ValueOperations<String,String> value = redisTemplate.opsForValue();
        //根据key值查询
        String redisCode = value.get(number);
        if (code.equals(redisCode)){
            //return "成功";
            return  true;

        }
        return  false;
        //return redisCode==null ? "请先获取验证码在进行校验！" : "错误";
    }
    //验证邀请码
    @PostMapping("/invicode")
    @ResponseBody
    public boolean checkInvicode(String data)
    {
        return userService.checkInvicodeUnique(data);
    }
    @PostMapping("/register")
    @ResponseBody
    public boolean ajaxRegister(@Validated SysMember user)
    {

        if (StringUtils.isNotEmpty(user.getUsername()) && !userService.checkPhoneUnique(user.getUsername()))
        {
            return false;
        }
        if(PhoneUtil.isPhone(user.getUsername()))
            user.setPhone(user.getUsername());
        user.setIinvicode(IdUtils.generateRandomCode(6));
        //昵称
        user.setNickname(user.getUsername());
        user.setRegip(ShiroUtils.getIp());
        user.setSalt(ShiroUtils.randomSalt());
        user.setPassword(passwordService.encryptPassword(user.getUsername(), user.getPassword(), user.getSalt()));
        user.setRegdate(DateUtils.getNowDate());
        user.setInsertdate(DateUtils.getNowDate());

       return  userService.insertSysMember(user);

    }
    //修改密码
    @GetMapping(value = {"/change"})
    public String change(ModelMap model) {

        SysMember sysMember = iSysMemberService.selectSysMemberByUserid(ShiroUtils.getSysMember().getUserid());
        model.put("user",sysMember);
        getabout(model);
        List<SysLoginset> sysLoginsetList = iSysLoginsetService.selectSysLoginsetList(new SysLoginset());
        //判断登录登录还是邮箱
        Boolean isphone = false;
        Boolean isemail = false;
        for (int i=0;i<sysLoginsetList.size();i++)
        {
            if (sysLoginsetList.get(i).getId()==3)
                isphone = sysLoginsetList.get(i).getState()>0?true:false;
            if (sysLoginsetList.get(i).getId()==4)
                isemail = sysLoginsetList.get(i).getState()>0?true:false;
        }
        model.put("isphone",isphone);
        model.put("isemail",isemail);
        //****************************/
        //************注册选项 *//
        SysRegset regset = iSysRegsetService.selectSysRegsetList(new SysRegset()).get(0);
        model.put("regset",regset);
        return "change";
    }
    @PostMapping (value = {"/c/ycaptcha"})
    @ResponseBody
    public Boolean change(DataParam dataParam) {

        return  ShiroUtils.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY).equals(dataParam.getData());
    }
    @GetMapping({"/protocol"})
    @ResponseBody
    public String protocol() {
        return "";
    }
    //修改密码
    @PostMapping (value = {"/change/password"})
    @ResponseBody
    public Integer changepassword(PasswordParam passwordParam) {
        //修改
        //SysMember user = iSysMemberService.selectSysMemberByUserid(ShiroUtils.getSysMember().getUserid());
        SysMember user = iSysMemberService.selectUserByLoginName(passwordParam.getUsername());
        user.setPassword(passwordService.encryptPassword(user.getUsername(), passwordParam.getPassword(), user.getSalt()));
        return  iSysMemberService.updateSysMember(user);
    }
    //找回密码
    //修改密码
    @GetMapping(value = {"forget.html"})
    public String forget(ModelMap model) {
        getabout(model);
        List<SysLoginset> sysLoginsetList = iSysLoginsetService.selectSysLoginsetList(new SysLoginset());
        //判断登录登录还是邮箱
        Boolean isphone = false;
        Boolean isemail = false;
        for (int i=0;i<sysLoginsetList.size();i++)
        {
            if (sysLoginsetList.get(i).getId()==3)
                isphone = sysLoginsetList.get(i).getState()>0?true:false;
            if (sysLoginsetList.get(i).getId()==4)
                isemail = sysLoginsetList.get(i).getState()>0?true:false;
        }
        model.put("isphone",isphone);
        model.put("isemail",isemail);
        //****************************/
        //************注册选项 *//
        SysRegset regset = iSysRegsetService.selectSysRegsetList(new SysRegset()).get(0);
        model.put("regset",regset);
        return "forget";
    }
    @PostMapping("/c/user_valid")
    @ResponseBody
    public boolean uservalid(String data)
    {
        return !userService.checkPhoneUnique(data);
    }
    @PostMapping("/test")
    @ResponseBody
    public long test()
    {

        SysMemberMapper iSysMemberService = SpringUtils.getBean(SysMemberMapper.class);
        SysMember sysMember = new SysMember();
        sysMember.setInsertdate(DateUtils.getNowDate());
        //sysMember.setVipdate(Date(LocalDateTime.now().plusDays(5));
        iSysMemberService.insertSysMember(sysMember);
        long userid = sysMember.getUserid();
        return userid;


    }

    @GetMapping("/qr")
    @ResponseBody
    public void getQr(@RequestParam("state") String state) {
        weChatService.getQr(state);
    }
    @GetMapping({"/gzh_pcin"})
    @ResponseBody
    public Boolean gzh_pcin(ModelMap model,HttpServletRequest request) {

        //String wxopenid = (String) redisTemplate.opsForValue().get("wxopenid");
        Object wxopenid = ShiroUtils.getSession().getAttribute("userid");
        System.out.println("userid&&&&"+ShiroUtils.getSession().getAttribute("userid"));
        //System.out.println("userid&&&&"+ServletUtils.getSession().getAttribute("userid"));

        return (wxopenid!=null)?true:false;

    }
    @GetMapping("/wx/user/info")
    @ResponseBody
    public void userInfo(@RequestParam("code") String code, @RequestParam("state") String state,HttpServletRequest request) {
      AjaxResult ajaxResult = weChatService.userInfo(code, state);
      WxMpUser wxMpUser = (WxMpUser)(ajaxResult.get("data"));
      //System.out.println(wxMpUser.getHeadImgUrl());

      SysMember  sysMember = new SysMember();
      sysMember.setUsername("wei_"+wxMpUser.getOpenId());
      sysMember.setNickname(wxMpUser.getNickname());
      sysMember.setSex(wxMpUser.getSex()==1?"男":"女");
      sysMember.setOpenwx("wei_"+wxMpUser.getOpenId());
      sysMember.setPhoto(wxMpUser.getHeadImgUrl());
      sysMember.setAddress(wxMpUser.getProvince()+wxMpUser.getCity());
      sysMember.setIinvicode(IdUtils.generateRandomCode(6));
      sysMember.setRegdate(DateUtils.getNowDate());
      sysMember.setRegip(ShiroUtils.getIp());
      sysMember.setLogindate(DateUtils.getNowDate());
      sysMember.setRegfrom(4);
      sysMember.setSalt("111111");
      sysMember.setPassword(passwordService.encryptPassword(wxMpUser.getOpenId(), "111111", "111111"));
      if (userService.checkOpenidUnique(sysMember.getUsername()))
      {
             userService.insertSysMember(sysMember);

      }
        //HttpSession session = request.getSession();
        //session.setAttribute("userid", wxMpUser.getOpenId());
        redisTemplate.opsForValue().set(sysMember.getUsername(),true);

      EasyUsernameToken token = new EasyUsernameToken(sysMember.getUsername());
        Subject subject = SecurityUtils.getSubject();
        try
        {
            subject.login(token);
            //return  "redirect:https://wx.sishoe.com/";
        }
        catch (AuthenticationException e)
        {
            String msg = "用户或密码错误";
            if (StringUtils.isNotEmpty(e.getMessage()))
            {
                msg = e.getMessage();
                System.out.println(msg);
            }
            //return  "redirect:/login";
        }

        //return  sysMember.getUsername();
    }
    @GetMapping("/oauth/alipay/callback")
    @ResponseBody
    public  void callback(AuthCallback callback) {
        //AuthRequest authRequest = factory.get(type);
       // AuthResponse response = authRequest.login(callback);
        //log.info("【response】= {}", JSONUtil.toJsonStr(response));
        //return response;
        AuthRequest authRequest = getAuthRequest();
        AuthResponse<AuthUser> response = authRequest.login(callback);
        AuthUser wxMpUser = response.getData();
        SysMember  sysMember = new SysMember();
        sysMember.setUsername("alipay_"+wxMpUser.getRawUserInfo().getString("openId"));
        sysMember.setNickname(wxMpUser.getNickname());
        sysMember.setOpenwx("alipay_"+wxMpUser.getRawUserInfo().getString("openId"));
        sysMember.setPhoto(wxMpUser.getAvatar());

        sysMember.setIinvicode(IdUtils.generateRandomCode(6));
        sysMember.setRegdate(DateUtils.getNowDate());
        sysMember.setRegip(ShiroUtils.getIp());
        sysMember.setLogindate(DateUtils.getNowDate());
        sysMember.setRegfrom(4);
        sysMember.setSalt("111111");
        sysMember.setPassword(passwordService.encryptPassword(wxMpUser.getRawUserInfo().getString("openId"), "111111", "111111"));
        if (userService.checkOpenidUnique(sysMember.getUsername()))
        {
            userService.insertSysMember(sysMember);
        }

        EasyUsernameToken token = new EasyUsernameToken(sysMember.getUsername());
        Subject subject = SecurityUtils.getSubject();
        try
        {
            subject.login(token);
            ServletUtils.getResponse().sendRedirect("https://wenku.sishoe.com");

        }
        catch (AuthenticationException e)
        {
            String msg = "用户或密码错误";
            if (StringUtils.isNotEmpty(e.getMessage()))
            {
                msg = e.getMessage();
                System.out.println(msg);
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
    @GetMapping("/alilogin/{type}")
    @ResponseBody
    public void login(@PathVariable String type) throws IOException {
        AuthRequest authRequest = getAuthRequest();
        ServletUtils.getResponse().sendRedirect(authRequest.authorize(AuthStateUtils.createState()));
    }
    private AuthRequest getAuthRequest() {
        SysLoginset  sysLoginset = new SysLoginset();
        sysLoginset = iSysLoginsetService.selectSysLoginsetById(6);
        JSONObject jsonObject = JSON.parseObject(sysLoginset.getValue());
        //System.out.println(jsonObject.getString("AAPPID"));
        System.out.println(jsonObject.getString(serverConfig.getUrl()+"/oauth/alipay/callback"));
        return new AuthAlipayRequest(AuthConfig.builder()
                .clientId(jsonObject.getString("AAPPID"))
                .clientSecret(jsonObject.getString("ALIKEY"))
                .alipayPublicKey(jsonObject.getString("PALIKEY"))
                .redirectUri(serverConfig.getUrl()+"/oauth/alipay/callback")
                .build());
        /*return new AuthGiteeRequest(AuthConfig.builder()
                .clientId("aa2241e6a87f1c2a6291604136b55f3880634498efcc22c4cce8013acc6eac55")
                .clientSecret("1cabff24bc760eb6fb34f52c9ccf5c377fa3232684897925777ae5a0d7d3790f")
                .redirectUri("https://wx.sishoe.com/oauth/gitee/callback")
                .build());*/


    }
   /* public  void getabout(ModelMap modelMap)
    {
        HashMap<String, List<SysAbout>> abouthash = new HashMap<String,List<SysAbout>>();
        List<SysAbout> tem1 = new ArrayList<SysAbout>();
        SysAbout  sysAbout = new SysAbout();
        sysAbout.setState(1);
        List<SysAbout> sysAboutList = iSysAboutService.selectSysAboutList(sysAbout);
        for(int i=0;i<sysAboutList.size();i++)
        {
            if (abouthash.containsKey(sysAboutList.get(i).getGroupname())) {
                abouthash.get(sysAboutList.get(i).getGroupname()).add(sysAboutList.get(i));
            } else {
                tem1.clear();
                tem1.add(sysAboutList.get(i));
                List<SysAbout> list = new ArrayList<SysAbout>(tem1);
                abouthash.put(sysAboutList.get(i).getGroupname(), list);
            }
        }
        modelMap.put("site",iSysSiteService.selectSysSiteList(new SysSite()).get(0));
        modelMap.put("about",abouthash);

    }*/
}

